package com.twd.allcomponent.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.HashMap;
import java.util.Map;

public class RespBean extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public RespBean() {
        put("code", 0);
        put("msg", "success");
    }

    public RespBean setData(Object data) {
        put("data", data);
        return this;
    }

    // 利用fastjson进行反序列化
    public <T> T getData(TypeReference<T> typeReference) {
        // 默认是map
        Object data = get("data");
        String jsonString = JSON.toJSONString(data);
        return JSON.parseObject(jsonString, typeReference);
    }

    // 利用fastjson进行反序列化
    public <T> T getData(String key, TypeReference<T> typeReference) {
        // 默认是map
        Object data = get(key);
        String jsonString = JSON.toJSONString(data);
        return JSON.parseObject(jsonString, typeReference);
    }

    public static RespBean error() {
        return error(500, "未知异常，请联系管理员");
    }

    public static RespBean error(String msg) {
        return error(500, msg);
    }

    public static RespBean error(int code, String msg) {
        RespBean r = new RespBean();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static RespBean ok(String msg) {
        RespBean r = new RespBean();
        r.put("msg", msg);
        return r;
    }

    public static RespBean ok(Map<String, Object> map) {
        RespBean r = new RespBean();
        r.putAll(map);
        return r;
    }

    public static RespBean ok() {
        return new RespBean();
    }

    @Override
    public RespBean put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public Integer getCode() {

        return (Integer) this.get("code");
    }

}
